using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using HybridWebSocket;
using System;
using UnityEngine.UI; 
using System.Linq;
public class updateRoom : MonoBehaviour
{
    // Start is called before the first frame update
    private WebSocket ws; // WebSocket 实例
    public string IP;
    public GameObject[] RoomButtonList;
    public int[] RoomList;
    public Dropdown dropDown;
    public float requestCount;
    void Start()
    {
        // 创建 WebSocket 实例
        ws = WebSocketFactory.CreateInstance(IP);

        // 添加 OnOpen 事件监听器
        ws.OnOpen += () =>
        {
            Debug.Log("WS connected!");
            Debug.Log("WS state: " + ws.GetState().ToString());
        };

        // 添加 OnMessage 事件监听器
        ws.OnMessage += (byte[] msg) =>
        {
            RevAction(msg);
        };

        // 添加 OnError 事件监听器
        ws.OnError += (string errMsg) =>
        {
            Debug.Log("WS error: " + errMsg);
        };

        // 添加 OnClose 事件监听器
        ws.OnClose += (WebSocketCloseCode code) =>
        {
            Debug.Log("WS closed with code: " + code.ToString());
        };
        ws.Connect();

    }

    void OnDestroy()
    {
        if (ws != null)
        {
            ws.Close();
        }
    }
    
    void RevAction(byte[] msg)
    {
        
        for(int i=0;i<msg.Length/4;i++)
        {
            int roomHost=BitConverter.ToInt32(msg, i*4);
            Debug.Log(roomHost);
            RoomList[i]=roomHost;
            
        }
    }

    void FixedUpdate()
    {
        requestCount+=Time.fixedDeltaTime;
        if(requestCount>1f)
        {
            ws.Send(BitConverter.GetBytes(100));
            requestCount=0;
            for(int i=0;i<6;i++)
            {
                RoomList[i]=0;
            }
        }
            
        for(int i=0;i<6;i++)
        {
            RoomButtonList[i].GetComponent<enterRoom>().myHost=RoomList[i];

            Transform child = RoomButtonList[i].transform.GetChild(0);

            // 检查子对象是否有Text组件
            Text childText = child.gameObject.GetComponent<Text>();
            if (childText != null)
            {
                // 修改Text组件的文本
                if(RoomList[i]!=0)
                    childText.text = "房间号："+RoomList[i];
                else
                    childText.text = "";
            }
            
        }
    }

    // 添加房间
    public void AddRoom()
    {
        if ( ws.GetState() == WebSocketState.Open)
            ws.Send(BitConverter.GetBytes(dropDown.value+1));
        else
            Debug.Log(111);
    }
}
